/*
 * @Description: 层级组件 - 标题、功能组件
 * @Author: Rfan
 * @Date: 2022-06-21 10:25:48
 * @LastEditTime: 2023-03-03 10:13:01
 */

import { ReactNode, useEffect, useMemo, useState } from 'react';
import { Button, Divider, Dropdown, Menu, MenuProps, Space } from 'antd';
import classNames from 'classnames/bind';
import AddArchiveItem from './optBtns/AddArchiveItem';
import { useLevelTableContext } from '../contexts/LevelTableContext';
import ExportOpt from './optBtns/ExportOpt';
import GenerateArcNo from './optBtns/GenerateArcNo';
import BreakUpFilesBtn from './optBtns/BreakUpFiles';
import LinkResourceBtn from './optBtns/LinkResource';
import AddAppraisalBtn from './optBtns/AddAppraisal';
import { DownOutlined } from '@ant-design/icons';
import FormatConversion from './optBtns/FormatConversion';
import RecordDownload from '@/components/functionalBtns/RecordDownload';
import Circulation from './optBtns/Circulation';
import AdditionalRecordBtn from './optBtns/AdditionalRecordBtn';
import CopyCreateBtn from './optBtns/CopyCreateBtn';
import { selectItemByKey } from '@/utils/list';
import InsertArchiveItem from './optBtns/InsertArchiveItem';
import FileMerge from './optBtns/FileMerge';
import Reorder from './optBtns/Reorder';
import ReturnArchives from './optBtns/ReturnArchives';
import GroupReorder from './optBtns/GroupReorder';
import TransferFiles from './optBtns/TransferFiles';
import PackBox from './optBtns/PackBoxBtn';
import UnpackBox from './optBtns/UnpackBoxBtn';
import PrintBtn from './optBtns/PrintBtn';
import { fetchMetadata } from '@/api/metadata';
import { QUERY_METADATA_NORMAL } from '@/view/system/Metadata/constants';
import styles from '../styles/levelTable.module.scss';
import FilterBtn from './optBtns/FilterBtn';
import HandoverTasksBtn from './optBtns/HandoverOpt/HandoverTasksBtn';
import ImportArchivesBtn from './optBtns/ImportArchivesBtn';
import DescWithImg from '@/components/LevelTable/componentes/optBtns/DescWithImg';

const cx = classNames.bind(styles);

interface ILevelOperateProps {
  title?: ReactNode;
  operates?: ReactNode;
  base?: any;
}

const LevelOperate = (props: ILevelOperateProps) => {
  const { operates, title } = props;
  const { list, baseInfo, upperInfo, selectItems, setFilterFields } = useLevelTableContext();
  const { level, levelNum } = baseInfo;

  // 选中的条目对象
  const [selectObj, setSelectObj] = useState(null);

  useEffect(() => {
    if (selectItems && selectItems.length === 1) {
      setSelectObj(selectItemByKey(selectItems[0], list));
    }
  }, [selectItems]);

  useEffect(() => {
    if (baseInfo.atType) {
      const params = {
        metadataFieldType: QUERY_METADATA_NORMAL,
        coordinate: {
          atType: baseInfo.atType,
          atCode: baseInfo.atCode,
          level: baseInfo.level
        }
      };
      fetchMetadata(params).then((res) => {
        setFilterFields(res.data);
      });
    }
  }, [baseInfo]);

  // 增加
  const addArchiveDialog = useMemo(
    () => (
      <>
        {baseInfo.level !== 0 && (
          <AddArchiveItem
            coordinate={{
              atCode: baseInfo.atCode,
              atType: baseInfo.atType,
              level: baseInfo.level
            }}
            upper={upperInfo}
            onSave={(data: any) => {}}
          />
        )}
      </>
    ),
    [baseInfo]
  );
  // 流转
  const circulation = useMemo(() => <Circulation />, [baseInfo]);
  // 退回
  const returnArchives = useMemo(() => <ReturnArchives list={selectObj} />, [selectObj]);
  // 导出
  const exportOptDialog = useMemo(() => <ExportOpt info={baseInfo} />, [baseInfo]);
  // 生成档号
  const generateDialog = useMemo(() => <GenerateArcNo info={baseInfo} />, [baseInfo]);
  // 打散
  const breakUpFilesDialog = useMemo(
    () => <BreakUpFilesBtn onSave={(data: any) => {}} />,
    [baseInfo]
  );
  // 挂接
  const linkResourceDialog = useMemo(() => <LinkResourceBtn />, [baseInfo]);
  // 加入鉴定
  const addAppraisal = useMemo(() => <AddAppraisalBtn />, [baseInfo]);
  // 格式转换
  const formatConversion = useMemo(() => <FormatConversion />, [baseInfo]);
  // 补录
  const additionalRecordDialog = useMemo(
    () => (
      <AdditionalRecordBtn
        coordinate={{
          atCode: baseInfo.atCode,
          atType: baseInfo.atType,
          level: baseInfo.level
        }}
        data={selectObj}
        onSave={(data: any) => {
          console.log('save data', data);
        }}
      />
    ),
    [baseInfo, selectObj]
  );

  // 复制创建
  const CopyCreateDialog = useMemo(
    () => (
      <CopyCreateBtn
        coordinate={{
          atCode: baseInfo.atCode,
          atType: baseInfo.atType,
          level: baseInfo.level
        }}
        data={selectObj}
      />
    ),
    [baseInfo, selectObj]
  );

  // 加入指定案卷
  const transferFiles = useMemo(() => <TransferFiles selectItems={selectItems} />, [selectItems]);

  // 插录弹窗
  const insertArchiveDialog = useMemo(
    () => (
      <>
        {baseInfo.level !== 0 && (
          <InsertArchiveItem
            coordinate={{
              atCode: baseInfo.atCode,
              atType: baseInfo.atType,
              level: baseInfo.level
            }}
            data={selectObj}
            onSave={(data: any) => {
              console.log('save data', data);
            }}
          />
        )}
      </>
    ),
    [baseInfo, selectObj]
  );

  // 调序弹窗
  const reorderDialog = useMemo(() => <Reorder selectItems={selectItems} />, [selectItems]);

  // 同分组调序
  const groupReorder = useMemo(() => <GroupReorder selectItems={selectItems} />, [selectItems]);

  // 下载
  const recordDownload = useMemo(
    () => <RecordDownload selectItems={selectItems} baseInfo={baseInfo} />,
    [selectItems]
  );

  // 文件合并
  const fileMerge = useMemo(
    () => <FileMerge selectItems={selectItems} baseInfo={baseInfo} />,
    [selectItems, baseInfo]
  );

  // 文件合并
  const print = useMemo(() => <PrintBtn selectItems={selectItems} />, [selectItems, baseInfo]);

  const handoverTasks = useMemo(
    () => <HandoverTasksBtn selectItems={selectItems} info={baseInfo} />,
    [selectItems]
  );

  // 导入
  const importArchivesBtn = useMemo(
    () => <ImportArchivesBtn baseInfo={baseInfo} />,
    [selectItems, baseInfo]
  );

  // 装盒
  const packBox = useMemo(
    () => (
      <PackBox
        coordinate={{
          atCode: baseInfo.atCode,
          atType: baseInfo.atType,
          level: baseInfo.level
        }}
        data={selectObj}
        onSave={(data: any) => {
          console.log('save data', data);
        }}
      />
    ),
    [selectObj]
  );

  // 拆盒
  const unpackBox = useMemo(() => <UnpackBox />, [selectItems]);

  // 看图著录
  const descWithImgBtn = useMemo(
    () => <DescWithImg selectData={selectObj} />,
    [baseInfo, selectObj]
  );

  /**
   * @description: 非最低级，非电子文件级
   * @return {boolean} 是否符合
   */
  const notLowest = (): boolean => {
    return level > 0;
  };

  /**
   * @description: 非最高级
   * @return {boolean} 是否符合
   */
  const notHighest = (): boolean => {
    return levelNum > 1;
  };

  /**
   * @description: 最低级，电子文件级
   * @return {boolean} 是否符合
   */
  const isLowest = (): boolean => {
    return level === 0;
  };

  /**
   * @description: 最高级
   * @return {boolean} 是否符合
   */
  const isHighest = (): boolean => {
    return levelNum === 1;
  };

  /**
   * @description: 是否为某个级别
   * @param {number} levelArr
   * @return {boolean} 是否符合
   */
  const isLevel = (levelArr: number[]): boolean => {
    return levelArr.indexOf(level) >= 0;
  };

  const handleMenuClick: MenuProps['onClick'] = (evt) => {
    console.log('click', evt);
  };

  const moreMenuItems = [
    notLowest() && {
      label: CopyCreateDialog,
      key: 'copyCreate'
    },
    level === 1 &&
      notHighest() && {
        label: transferFiles,
        key: 'transferToOther'
      },
    notLowest() && {
      label: (
        <Button type="text" size="small">
          批量修改
        </Button>
      ),
      key: 'batchEdit'
    },
    isLevel([1]) && {
      label: fileMerge,
      key: 'join'
    },
    notLowest() && {
      label: importArchivesBtn,
      key: 'import'
    },
    {
      label: print,
      key: 'print'
    },
    level === 1 && {
      label: (
        <Button type="text" size="small">
          原文批量挂接
        </Button>
      ),
      key: 'batchLink'
    },
    level === 1 && {
      label: descWithImgBtn,
      key: 'descWithImg'
    },
    isHighest() && {
      label: packBox,
      key: 'packBox'
    },
    isHighest() && {
      label: unpackBox,
      key: 'splitFromBox'
    }
  ];

  return (
    <div className={cx('level-operate')}>
      <div className={cx('title')}>
        {title === undefined
          ? baseInfo.levelName?.slice(0, -1)
            ? `${baseInfo.levelName?.slice(0, -1)}列表`
            : ''
          : title}
      </div>
      <div className={cx('operate')}>
        <Space wrap>
          {operates === undefined ? (
            <>
              {/* {isHighest() && addAppraisal} */}
              {notLowest() && addArchiveDialog}
              {notLowest() && <Button>删除</Button>}
              {notLowest() && additionalRecordDialog}
              {notLowest() && insertArchiveDialog}
              {level === 1 && reorderDialog}
              {isHighest() && returnArchives}
              {isHighest() && circulation}
              {isHighest() && groupReorder}
              {level === 1 && <Button>拆离</Button>}
              {level === 2 && breakUpFilesDialog}
              {isHighest() && generateDialog}
              {isHighest() && exportOptDialog}
              {isHighest() && <Button>规范性检测</Button>}
              {level === 0 && <Button>预览</Button>}
              {level === 0 && formatConversion}
              {level === 0 && linkResourceDialog}
              {level === 0 && recordDownload}
              {level === 0 && <Button>清空电子文件</Button>}
              {isHighest() && handoverTasks}
              {/* 放入更多按钮 */}
              {/* {notLowest() && <Button disabled>复制创建</Button>} */}
              {/* {level === 1 && <Button disabled>转移到其它案卷</Button>} */}
              {/* {notLowest() && <Button disabled>批量修改</Button>} */}
              {/* {level === 1 && <Button disabled>合并</Button>} */}
              {/* <Button disabled>导入</Button> */}
              {/* <Button disabled>打印</Button> */}
              {/* {level === 1 && <Button disabled>原文批量挂接</Button>} */}
              {/* {isLevel([1, 2]) && <Button disabled>装盒</Button>} */}
              {/* {isLevel([1, 2]) && <Button disabled>从盒中拆离</Button>} */}

              {/* 暂时屏蔽 */}
              {/* {level === 0 && <Button disabled>原文删除</Button>} */}

              {/* 暂时增加 */}
              <Dropdown overlay={<Menu onClick={handleMenuClick} items={moreMenuItems} />}>
                <Button>
                  <Space>
                    更多
                    <DownOutlined />
                  </Space>
                </Button>
              </Dropdown>
              <Divider type="vertical" />
              <FilterBtn />
              {/* {[1, 2].indexOf(level) >= 0 && <Button disabled>分组</Button>} */}
              {/* {[1, 2].indexOf(level) >= 0 && <Button disabled>同分组调序</Button>} */}
              {/* <Button>在线移交</Button> */}
            </>
          ) : (
            operates
          )}
        </Space>
      </div>
    </div>
  );
};

export default LevelOperate;
